<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="props.title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button v-if="!id" @click="openEquipmentWindow()"
          >引入资产卡片</el-button
        >
        <el-button
          @click="saveAndSubmit()"
          v-if="!id && $permission('measuringInstrument:saveAndSubmit')"
          >保存并提交</el-button
        >
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            :list-type-info="listTypeInfo"
            :image-field="formInfo.imageField"
          >
            <template v-slot:form-managerUserName>
              <el-input
                v-model="formInfo.data.managerUserName"
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择检定责任人"
              >
                <template #append>
                  <el-icon @click="openResponsibleUserList"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>证照信息</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="licenseInfo.ref"
            :disabled="licenseInfo.disabled"
            :data="licenseInfo.data"
            :field-list="licenseInfo.fieldList"
            :rules="licenseInfo.rules"
            :label-width="licenseInfo.labelWidth"
          >
            <template v-slot:form-licenseNumber>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择证照"
                v-model="licenseInfo.data.licenseNumber"
              >
                <template #append>
                  <el-icon @click="openLicenseList"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>上次检定信息</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="verificationInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="verificationInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="verificationInfo.labelWidth"
            ><template v-slot:form-verificationDate>
              <el-date-picker
                v-model="formInfo.data.verificationDate"
                value-format="YYYY-MM-DD"
              />
              <!-- :disabled-date="checkTimePickerOptions.disabledDate" -->
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>检定计划</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="verificationPlan.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="verificationPlan.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-taskCreateEarlyDay>
              <el-input-number
                v-model="formInfo.data.taskCreateEarlyDay"
                controls-position="right"
                :min="0"
                :max="999999999999999999"
                placeholder="请输入内容"
                :precision="1"
                style="width: 65%; display: inline-block"
              ></el-input-number>
              <select-model
                v-model.trim="formInfo.data.remindTask"
                typeCode="remind_time_type"
                :onlyShowOption="['3']"
                style="width: 35%"
              />
            </template>
            <template v-slot:form-taskWarnEarlyTime>
              <el-input-number
                v-model="formInfo.data.taskWarnEarlyTime"
                controls-position="right"
                :min="0"
                :max="999999999999999999"
                placeholder="请输入内容"
                :precision="1"
                style="width: 65%; display: inline-block"
              ></el-input-number>
              <select-model
                v-model.trim="formInfo.data.taskWarnUnit"
                typeCode="remind_time_type"
                style="width: 35%"
              />
            </template>
          </page-form>
        </div>
      </div>
    </NewFullScreen>
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :highlightRow="true"
      :checkBox="false"
      :tableKey="selectAssetInfo.tableKey"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :api="selectAssetInfo.api"
      @callback="callBackAsset"
    />
    <SelectLicense
      v-if="selectLicenseInfo.visible"
      @callback="selectLicense"
      :saveEmpty="true"
      v-model:query="selectLicenseInfo.query"
      v-model:showDialog="selectLicenseInfo.visible"
    />
    <select-users
      v-if="userInfo.visible"
      v-model:show-dialog="userInfo.visible"
      :api="userInfo.api"
      :save-empty="false"
      :checked-list="
        userInfo.row.checkBox ? userInfo.checked[userInfo.row.value] : []
      "
      :check-box="false"
      :highlight-row="true"
      @callback="callBackUser"
    />
  </div>
</template>

<script setup name="measuringInstrumentModify">
import utils from '@/common/js/utils' // 公共方法
import SelectAsset from '@/views/asset/assetManage/assetAcceptance/addAsset'
import PageForm from '@/components/PageForm/index'
import SelectLicense from '@/components/SelectLicense/index'
import { getRrgUserList } from '@/api/base.js'
import {
  detailMeasuringInstrument,
  createMeasuringInstrument,
  createMeasuringInstrumentAndSave,
  updateMeasuringInstrument,
} from '@/api/equipment.js'
import { getCoreCodeStatus, getAssetCardCustomizePage } from '@/api/core.js'
import axios from 'axios'
import { getUnitAll } from '@/api/core.js'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
})
const userInfo = ref({
  visible: false,
  api: getRrgUserList,
  row: {},
  data: {},
  checked: {},
})
const formInfo = ref({
  ref: null,
  data: {
    status: 1,
    remindTask: 3,
    taskWarnUnit: 1,
  },
  imageField: {
    label: '计量器具照片',
    value: 'pictureList',
    fileType: ['jpg', 'png'],
    fileSize: 1,
    btnDisabled: false,
    action: axios.defaults.baseURL + '/pub/uploadfile',
  },
  fieldList: [
    {
      label: '器具标准名称',
      value: 'commonName',
      type: 'input',
    },
    {
      label: '资产名称',
      value: 'assetName',
      type: 'input',
      disabled: true,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '器具编码',
      value: 'code',
      type: 'input',
      show: true,
      disabled: !!props.id,
    },
    /* {
      label: '是否启用',
      value: 'enableStatus',
      type: 'radio-model',
      code: 'enabled_type',
    }, */
    {
      label: '专业分类',
      value: 'professionalClassification',
      type: 'select-model',
      code: 'professional_classification',
      checkDefault: true,
    },
    {
      label: '是否强检',
      value: 'mandatoryTest',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '拼音码',
      value: 'pinyinCode',
      type: 'input',
    },
    {
      label: '计量单位',
      value: 'unitId',
      type: 'select',
      required: false,
      list: 'unitList',
      filterable: true,
    },
    {
      label: '准确度',
      value: 'accuracy',
      type: 'input',
    },
    {
      label: '品牌',
      value: 'trademark',
      type: 'input',
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
    },
    {
      label: '测量范围',
      value: 'measurementRange',
      type: 'input',
    },
    {
      label: '检定类型',
      value: 'verificationType',
      type: 'select-model',
      clearable: true,
      code: 'verification_type',
    },
    {
      label: '主要参数',
      value: 'mainParameter',
      type: 'input',
    },
    {
      label: '出厂编号',
      value: 'factoryNo',
      type: 'input',
    },
    {
      label: '检定责任人',
      value: 'managerUserName',
      asValue: 'managerUser',
      type: 'slot',
      required: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    commonName: [
      { required: true, message: '请输入设备名称', trigger: 'change' },
    ],
    code: [
      { required: true, message: '请输入设备编码', trigger: 'change' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    verificationPeriod: [
      {
        required: true,
        validator: proxy.$validate.naturalnumber1,
        trigger: 'blur',
      },
    ],
    managerUserName: [
      { required: true, message: '请选择检定责任人', trigger: 'change' },
    ],
    /* verificationDate: [
      {
        required: true,
        message: '请选择检定日期',
        trigger: 'change',
      },
    ], */
    taskCreateEarlyDay: [
      {
        validator: validateRemindTask,
        trigger: ['blur', 'change'],
      },
      { required: false, message: '请输入提醒时间', trigger: 'blur' },
    ],
    taskWarnEarlyTime: [
      {
        validator: validateRemind,
        trigger: ['blur', 'change'],
      },
      {
        required: false,
        message: '请输入任务创建时间',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const verificationInfo = ref({
  fieldList: [
    {
      label: '上次检定日期',
      value: 'verificationDate',
      type: 'slot',
      placeholder: false,
    },
    {
      label: '上次检定结果',
      value: 'verificationResult',
      type: 'select-model',
      clearable: true,
      code: 'verification_result',
    },
    {
      label: '上次检定证书编号',
      value: 'verificationCertificateNumber',
      type: 'input',
    },
    {
      label: '上次检定单位',
      value: 'verificationUnit',
      type: 'input',
    },
  ],
  labelWidth: '140px',
})
const verificationPlan = ref({
  fieldList: [
    {
      label: '检定周期(月)',
      value: 'verificationPeriod',
      type: 'number',
      min: 1,
      max: 9999,
    },
    {
      label: '任务创建于：任务开始前',
      value: 'taskCreateEarlyDay',
      type: 'slot',
      require: true,
    },
    {
      label: '任务提醒于：任务开始前',
      value: 'taskWarnEarlyTime',
      type: 'slot',
      require: true,
    },
    {
      label: '下次检定日期',
      value: 'validityDate',
      type: 'date',
      placeholder: false,
      disabled: false,
      required: true,
    },
  ],
})
const licenseInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '是否关联证照',
      value: 'needLicense',
      type: 'radio-model',
      code: 'need_or_no_need_no',
      required: true,
      show: true,
    },
    {
      label: '证号',
      value: 'licenseNumber',
      type: 'slot',
      required: true,
    },
    {
      label: '证照名称',
      value: 'licenseName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '英文名称',
      value: 'enName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '证照生效日期',
      value: 'licenseBeginDate',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '证照失效日期',
      value: 'licenseEndDate',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
    {
      label: '生产厂家',
      value: 'brandName',
      type: 'input',
      disabled: true,
      placeholder: false,
    },
  ],
  rules: {
    licenseNumber: [
      { required: true, message: '请选择证号', trigger: 'change' },
    ],
  },
})
const listTypeInfo = ref({
  licenseList: [],
  brandList: [],
  unitList: [],
})
const selectLicenseInfo = ref({
  visible: false,
  query: {
    status: '1',
    licenseApplicationType: '2',
  },
})
const selectAssetInfo = ref({
  api: getAssetCardCustomizePage,
  visible: false,
  tableKey: 'addCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      isMetering: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {},
  },
})
const formRefs = ref(null)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    console.log(val)
    emits('update:visible', val)
  },
})

watch(
  () => licenseInfo.value.data.needLicense,
  (val) => {
    if (val == 1) {
      licenseInfo.value.rules.licenseNumber[0].required = true
    } else if (val == 0) {
      licenseInfo.value.rules.licenseNumber[0].required = false
    }
  }
)
watch(
  () => formInfo.value.data.verificationPeriod,
  (val) => {
    if (val != null && formInfo.value.data.verificationDate) {
      let date1 = new Date(formInfo.value.data.verificationDate)
      date1.setMonth(date1.getMonth() + formInfo.value.data.verificationPeriod)
      let month =
        date1.getMonth() + 1 > 9
          ? date1.getMonth() + 1
          : 0 + '' + (date1.getMonth() + 1)
      let date =
        date1.getDate() > 9 ? date1.getDate() : 0 + '' + date1.getDate()
      formInfo.value.data.validityDate =
        date1.getFullYear() + '-' + month + '-' + date
    }
  }
)
watch(
  () => formInfo.value.data.verificationDate,
  (val) => {
    if (val != null && formInfo.value.data.verificationPeriod) {
      let date1 = new Date(formInfo.value.data.verificationDate)
      date1.setMonth(date1.getMonth() + formInfo.value.data.verificationPeriod)
      let month =
        date1.getMonth() + 1 > 9
          ? date1.getMonth() + 1
          : 0 + '' + (date1.getMonth() + 1)
      let date =
        date1.getDate() > 9 ? date1.getDate() : 0 + '' + date1.getDate()
      formInfo.value.data.validityDate =
        date1.getFullYear() + '-' + month + '-' + date
    }
  }
)
onMounted(() => {
  getUnitList()

  if (props.id) {
    getDeatil()
  } else {
    getStatus()
  }
  formRefs.value = [
    licenseInfo.value.ref,
    formInfo.value.ref,
    verificationInfo.value.ref,
    verificationPlan.value.ref,
  ]
})
function openResponsibleUserList() {
  userInfo.value.visible = true
}
function callBackUser(row) {
  let type = Object.prototype.toString.call(row)
  row =
    type === '[object Object]' ? [row] : type === '[object Array]' ? row : []
  if (row.length) {
    formInfo.value.data.managerUser = row[0].id
    formInfo.value.data.managerUserName = row[0].name
  } else {
    formInfo.value.data.managerUser = ''
    formInfo.value.data.managerUserName = ''
  }
}
function validateRemindTask(rule, value, callback) {
  let taskWarnUnit = 0
  if (formInfo.value.data.taskWarnUnit == '1') {
    taskWarnUnit = 1
  } else if (formInfo.value.data.taskWarnUnit == '2') {
    taskWarnUnit = 60
  } else if (formInfo.value.data.taskWarnUnit == '3') {
    taskWarnUnit = 1440
  }
  let remindTask = 0
  if (formInfo.value.data.remindTask == '1') {
    remindTask = 1
  } else if (formInfo.value.data.remindTask == '2') {
    remindTask = 60
  } else if (formInfo.value.data.remindTask == '3') {
    remindTask = 1440
  }

  let taskWarnEarlyTime = formInfo.value.data.taskWarnEarlyTime || 0
  taskWarnEarlyTime = taskWarnUnit * taskWarnEarlyTime
  let taskCreateEarlyDay = formInfo.value.data.taskCreateEarlyDay || 0
  taskCreateEarlyDay = taskCreateEarlyDay * remindTask

  if (formInfo.value.data.taskWarnEarlyTime) {
    let num = taskCreateEarlyDay - taskWarnEarlyTime
    if (num < 5) {
      callback(new Error('任务创建时间必须大于提醒时间5分钟！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
function validateRemind(rule, value, callback) {
  let taskWarnUnit = 0
  if (formInfo.value.data.taskWarnUnit == '1') {
    taskWarnUnit = 1
  } else if (formInfo.value.data.taskWarnUnit == '2') {
    taskWarnUnit = 60
  } else if (formInfo.value.data.taskWarnUnit == '3') {
    taskWarnUnit = 1440
  }
  let remindTask = 0
  if (formInfo.value.data.remindTask == '1') {
    remindTask = 1
  } else if (formInfo.value.data.remindTask == '2') {
    remindTask = 60
  } else if (formInfo.value.data.remindTask == '3') {
    remindTask = 1440
  }

  let taskWarnEarlyTime = formInfo.value.data.taskWarnEarlyTime || 0
  taskWarnEarlyTime = taskWarnUnit * taskWarnEarlyTime
  let taskCreateEarlyDay = formInfo.value.data.taskCreateEarlyDay || 0
  taskCreateEarlyDay = taskCreateEarlyDay * remindTask
  if (formInfo.value.data.taskCreateEarlyDay) {
    let num = taskCreateEarlyDay - taskWarnEarlyTime
    console.log(taskCreateEarlyDay, taskWarnEarlyTime)
    if (num < 5) {
      callback(new Error('提醒时间必须小于任务创建时间5分钟！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
function openEquipmentWindow() {
  selectAssetInfo.value.visible = true
}
function callBackAsset(data) {
  selectAssetInfo.value.visible = false
  if (data && data.id) {
    formInfo.value.data.assetName = data.assetName
    formInfo.value.data.commonName = data.assetName
    formInfo.value.data.assetId = data.id
    formInfo.value.data.assetCode = data.assetCode
    formInfo.value.data.unitId = data.unitId === -2 ? '' : data.unitId
    formInfo.value.data.standard = data.standard
    formInfo.value.data.trademark = data.mark
  }
}
const getDeatil = () => {
  detailMeasuringInstrument(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      formInfo.value.data = data
      formInfo.value.data['remindTask'] = 3
      formInfo.value.data['unitId'] = data.unitId == -2 ? '' : data.unitId
      formInfo.value.data['professionalClassification'] =
        data.professionalClassification == -2
          ? ''
          : data.professionalClassification
      formInfo.value.data.taskWarnEarlyTime =
        data.taskWarnEarlyTime < 0 ? null : data.taskWarnEarlyTime
      formInfo.value.data.taskCreateEarlyDay =
        data.taskCreateEarlyDay < 0 ? null : data.taskCreateEarlyDay
      licenseInfo.value.data = {
        needLicense: data.needLicense,
        needLicenseValue: data.needLicenseValue,
        licenseNumber: data.licenseNumber,
        licenseTypeValue: data.licenseTypeValue,
        licenseName: data.licenseName,
        licenseBeginDate: data.licenseBeginDate,
        licenseEndDate: data.licenseEndDate,
        brandName: data.brandName,
        enName: data.enName,
        licenseId: data.licenseId,
        brandId: data.brand,
      }
      if (formInfo.value.data.picture) {
        formInfo.value.data.pictureList = utils.splitArr(
          formInfo.vlaue.data.picture
        )
      }
    }
  })
}
function saveAndSubmit() {
  save(true)
}
const save = (isSaveAndSubmit) => {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const returnedTarget = Object.assign(
      formInfo.value.data,
      licenseInfo.value.data
    )
    if (returnedTarget.pictureList && returnedTarget.pictureList.length == 1) {
      returnedTarget.picture = returnedTarget.pictureList[0]
    } else {
      returnedTarget.picture = ''
    }
    if (props.id) {
      returnedTarget.id = props.id
    }
    const api = props.id
      ? updateMeasuringInstrument
      : isSaveAndSubmit === true
      ? createMeasuringInstrumentAndSave
      : createMeasuringInstrument
    api(returnedTarget).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify')
        emits('update:visible', false)
        formInfo.value.ref.validateField()
      }
    })
  })
}
// 选择征照
const selectLicense = (data) => {
  proxy.$nextTick(() => {
    if (data) {
      licenseInfo.value.data = {
        ...licenseInfo.value.data,
        licenseNumber: data.licenseNumber,
        licenseTypeValue: data.licenseTypeValue,
        licenseName: data.licenseName,
        licenseBeginDate: data.licenseBeginDate,
        licenseEndDate: data.licenseEndDate,
        brandName: data.brandName,
        enName: data.enName,
        licenseId: data.id,
        brandId: data.brand,
      }
    } else {
      licenseInfo.value.data = {
        ...licenseInfo.value.data,
        licenseNumber: '',
        licenseTypeValue: '',
        licenseName: '',
        licenseBeginDate: '',
        licenseEndDate: '',
        brandName: '',
        enName: '',
        licenseId: -2,
        brandId: -2,
      }
    }
  })
}
//获取计量单位列表
const getUnitList = () => {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
const openLicenseList = () => {
  selectLicenseInfo.value.visible = true
}
const getStatus = () => {
  getCoreCodeStatus({ codeType: '10' }).then((res) => {
    showFieldListItem(!res.data, 'code')
    formInfo.value.rules.code[1].required = !res.data
  })
}
const showFieldListItem = (show, nameValue) => {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
</script>

<style scoped>
.inputRefScanHidden {
  position: absolute;
  color: transparent;
  background-color: transparent;
  caret-color: black;
  border: none;
  outline: none;
  height: 30px;
  margin-left: 115px;
  width: 200px;
  z-index: 12;
}

.inputScan {
  ime-mode: disabled;
}

.active {
  display: none;
}
</style>
